
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  
  <title>Ubuntu 定时执行 python脚本 | 何妨吟啸且徐行</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="Ubuntu系统里有个定时任务的管理器 crontab，所以只需要编辑下定时任务，再重启下定时任务就行了。 因为是一台Ubuntu的服务器，一直开机的状态，所以开着定时任务就等于一直开着了。">
<meta property="og:type" content="article">
<meta property="og:title" content="Ubuntu 定时执行 python脚本">
<meta property="og:url" content="http://i007it.com/2021/02/08/Ubuntu%E5%AE%9A%E6%97%B6%E6%89%A7%E8%A1%8Cpython%E8%84%9A%E6%9C%AC/index.html">
<meta property="og:site_name" content="何妨吟啸且徐行">
<meta property="og:description" content="Ubuntu系统里有个定时任务的管理器 crontab，所以只需要编辑下定时任务，再重启下定时任务就行了。 因为是一台Ubuntu的服务器，一直开机的状态，所以开着定时任务就等于一直开着了。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-02-08T14:10:00.000Z">
<meta property="article:modified_time" content="2022-04-09T14:28:40.962Z">
<meta property="article:author" content="HDUZN hduzn@vip.qq.com">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="Linux">
<meta property="article:tag" content="Ubuntu">
<meta name="twitter:card" content="summary">
  
    <link rel="alternative" href="/atom.xml" title="何妨吟啸且徐行" type="application/atom+xml">
  
  
  
<link rel="stylesheet" href="/css/style.css">

  
    <link href="//fonts.useso.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <!--[if lt IE 9]><script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7/html5shiv.min.js"></script><![endif]-->
  
  

</head>

<body>
<div id="container">
  <div id="wrap">
    <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <nav id="upper-nav" class="inner">
      <a id="main-nav-toggle" class="nav-icon"></a>
      <div class="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        
          <a id="nav-github" class="nav-icon" target="_blank" rel="noopener" href="https://github.com/hduzn"></a>
        
      </div>
    </nav>
    <div id="header-title">
      
        <h1 id="blog-title-wrap">
          <a href="/" id="blog-title">一 蓑 烟 雨 任 平 生</a>
        </h1>
      
    </div>
    <div id="contenedor">
      <ul class="cube">
        <li class="cara">2022</li>
        <li class="cara">烟</li>
        <li class="cara">雨</li>
        <li class="cara">平</li>
        <li class="cara">生</li>
        <li class="cara">柒</li>
      </ul>
    </div>
    <nav id="main-nav">
      
        <a class="main-nav-link" href="/">首页</a>
      
        <a class="main-nav-link" href="/archives">归档</a>
      
        <a class="main-nav-link" href="/books">推荐阅读</a>
      
    </nav>
  </div>
</header>

    <div class="outer">
      <section id="main"><article id="post-Ubuntu定时执行python脚本" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <h3 href="/2021/02/08/Ubuntu%E5%AE%9A%E6%97%B6%E6%89%A7%E8%A1%8Cpython%E8%84%9A%E6%9C%AC/" class="article-date">
  <time datetime="2021-02-08T14:10:00.000Z" itemprop="datePublished">2021-02-08</time>
</h3>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/Linux/">Linux</a>
  </div>

  </div>
  <div class="article-inner">
  <div class="curve-down">
  <div class="fill-content">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      Ubuntu 定时执行 python脚本
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        
          <div id="toc" class="toc-article">
            <strong class="toc-title">文章目录</strong>
            <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%80%E3%80%81crontab%E5%91%BD%E4%BB%A4%E6%A0%BC%E5%BC%8F%E8%AF%A6%E8%A7%A3"><span class="toc-text">一、crontab命令格式详解</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E5%91%BD%E4%BB%A4%E6%A0%BC%E5%BC%8F%EF%BC%9A"><span class="toc-text">1.命令格式：</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E5%91%BD%E4%BB%A4%E4%B8%BE%E4%BE%8B"><span class="toc-text">2.命令举例</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%8C%E3%80%81%E7%BC%96%E8%BE%91%E5%AE%9A%E6%97%B6%E4%BB%BB%E5%8A%A1crontab%EF%BC%9A"><span class="toc-text">二、编辑定时任务crontab：</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%89%E3%80%81%E5%AE%9A%E6%97%B6%E6%89%A7%E8%A1%8Cpython-%E8%84%9A%E6%9C%AC"><span class="toc-text">三、定时执行python 脚本</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-python%E8%B7%AF%E5%BE%84"><span class="toc-text">1.python路径</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-python%E6%96%87%E4%BB%B6%E7%9A%84%E7%BB%9D%E5%AF%B9%E8%B7%AF%E5%BE%84"><span class="toc-text">2.python文件的绝对路径</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9B%9B%E3%80%81%E5%B0%8F%E7%BB%93"><span class="toc-text">四、小结</span></a></li></ol>
          </div>
        
        <p>Ubuntu系统里有个定时任务的管理器 crontab，所以只需要编辑下定时任务，再重启下定时任务就行了。</p>
<p>因为是一台Ubuntu的服务器，一直开机的状态，所以开着定时任务就等于一直开着了。</p>
<a id="more"></a>
<h2 id="一、crontab命令格式详解"><a href="#一、crontab命令格式详解" class="headerlink" title="一、crontab命令格式详解"></a>一、crontab命令格式详解</h2><h3 id="1-命令格式："><a href="#1-命令格式：" class="headerlink" title="1.命令格式："></a>1.命令格式：</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">m h dom mon dow <span class="built_in">command</span></span><br></pre></td></tr></table></figure>
<p>以上是缩写，全拼是：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">minute(m), hour(h), day of month(dom), month(mon), day of week(dow), <span class="built_in">command</span></span><br></pre></td></tr></table></figure>
<p><strong>含义</strong>：</p>
<ul>
<li>m: 每个小时的第几分钟执行，0-59</li>
<li>h: 第天的第几个小时执行，0-23</li>
<li>dom: 每月的第几天执行，1-31</li>
<li>mon: 每年的第几个月执行，1-12</li>
<li>dow: 每周的第几天执行，0-6（0表示星期天）</li>
<li>command: 定时执行的命令</li>
</ul>
<p><strong>其它</strong>：</p>
<ul>
<li>*： 表示任何时间</li>
<li>*/2: 表示每隔2分钟</li>
<li>-：表示区间，比如1-3</li>
<li>,：表示区间不连续，比如1,3,6</li>
</ul>
<h3 id="2-命令举例"><a href="#2-命令举例" class="headerlink" title="2.命令举例"></a>2.命令举例</h3><table>
<thead>
<tr>
<th>命令</th>
<th>含义</th>
<th>举例</th>
</tr>
</thead>
<tbody><tr>
<td>*  * * * * ifconfig</td>
<td>每天第一分钟都在执行ifconfig 命令</td>
<td>—</td>
</tr>
<tr>
<td>1 * * * * ifconfig</td>
<td>每天每个小时的第1分钟都在执行ifconfig 命令</td>
<td>01:01, 02:01, 03:01, 04:01……</td>
</tr>
<tr>
<td>0 9 * * * ifconfig</td>
<td>每天 9:00 执行ifconfig 命令</td>
<td>—</td>
</tr>
<tr>
<td>0 9 10 * * ifconfig</td>
<td>每个月的10号 9:00 执行ifconfig 命令</td>
<td>—</td>
</tr>
<tr>
<td>0 9 * * 1,2 ifconfig</td>
<td>每周一、周二 9:00 执行ifconfig 命令</td>
<td>—</td>
</tr>
</tbody></table>
<h2 id="二、编辑定时任务crontab："><a href="#二、编辑定时任务crontab：" class="headerlink" title="二、编辑定时任务crontab："></a>二、编辑定时任务crontab：</h2><p>命令：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">crontab -e</span><br></pre></td></tr></table></figure>
<p>第一次输入这个命令，会让你选择一下编辑软件，有4种，就直接输入 2 回车，选择用 vim。</p>
<ol>
<li>/bin/nano</li>
<li>/usr/bin/vim.basic</li>
<li>/usr/bin/vim.tiny</li>
<li>/bin/ed</li>
</ol>
<p>vim命令如果没用过不会用，也不用慌，会几个简单的命令就行了。上一篇文章 【Linux vim/vi 命令简单使用】有介绍。</p>
<p>打开了编辑定时任务后，里面有一堆前面带 # 的行，这些都是注释内容，不用管，其实也有关于定时任务设置的示例，有这么2行：</p>
<blockquote>
<p># at 5 a.m every week with:<br># 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/</p>
</blockquote>
<p>表示第2行的定时任务的意思是：在每周一的5:00 am 执行 tar 这条命令。</p>
<p>最后一行是命令格式：</p>
<blockquote>
<p># m h dom mon dow command</p>
</blockquote>
<p>在最下面添加自己的任务就可以了。</p>
<h2 id="三、定时执行python-脚本"><a href="#三、定时执行python-脚本" class="headerlink" title="三、定时执行python 脚本"></a>三、定时执行python 脚本</h2><p>注意，这里在定时任务中一定要用绝对路径。</p>
<p>比如平常运行 pythone脚本，因为添加到PATH环境变量中了，所以直接运行以下命令就可以了。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python3 test.py</span><br></pre></td></tr></table></figure>
<h3 id="1-python路径"><a href="#1-python路径" class="headerlink" title="1.python路径"></a>1.python路径</h3><p>所以首先要找到python3的路径，通过which命令就可以：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">which</span> python3</span><br></pre></td></tr></table></figure>
<p>得到结果比如是：<code>usr/bin/python3</code></p>
<h3 id="2-python文件的绝对路径"><a href="#2-python文件的绝对路径" class="headerlink" title="2.python文件的绝对路径"></a>2.python文件的绝对路径</h3><p>比如我的 test.py 存放在 <code>/home/ubuntu/python/code/</code> 中。</p>
<p>如果你不知道当前目录是什么，执行 <code>pwd</code> 命令就可以得到。</p>
<p>最后想把 test.py 定时运行输出的内容存放到 log文件中：<code>/home/ubuntu/tmp/test.log</code></p>
<p>所以，最终添加的这条定时任务记录是：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">0 17 * * * usr/bin/python3 /home/ubuntu/python/code/test.py &gt;&gt; /home/ubuntu/tmp/test.log</span><br></pre></td></tr></table></figure>
<p>表示：每天17点将执行 test.py，把输出内容打印到 test.log文件中。</p>
<h2 id="四、小结"><a href="#四、小结" class="headerlink" title="四、小结"></a>四、小结</h2><p>一共3步。</p>
<p>1.设计好自己想要执行的 python任务</p>
<p>比如：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">0 17 * * * usr/bin/python3 /home/ubuntu/python/code/test.py &gt;&gt; /home/ubuntu/tmp/test.log</span><br></pre></td></tr></table></figure>
<p>2.打开定时任务编辑，添加任务记录</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">crontab -e</span><br></pre></td></tr></table></figure>
<p>3.重启 cron服务</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sudo service cron restart</span><br></pre></td></tr></table></figure>
      
    </div>
    <footer class="article-footer">
      <div class="article-footer-content">
        
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Linux/" rel="tag">Linux</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Python/" rel="tag">Python</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Ubuntu/" rel="tag">Ubuntu</a></li></ul>

        <a data-url="http://i007it.com/2021/02/08/Ubuntu%E5%AE%9A%E6%97%B6%E6%89%A7%E8%A1%8Cpython%E8%84%9A%E6%9C%AC/" data-id="cl1t8bgm1001o54epcstqb3j8" class="article-share-link">分享到</a>
        
        
          <a href="/2021/02/08/Ubuntu%E5%AE%9A%E6%97%B6%E6%89%A7%E8%A1%8Cpython%E8%84%9A%E6%9C%AC/#comments" class="article-comment-link">
            <span class="post-comments-count valine-comment-count" data-xid="/2021/02/08/Ubuntu%E5%AE%9A%E6%97%B6%E6%89%A7%E8%A1%8Cpython%E8%84%9A%E6%9C%AC/" itemprop="commentCount"></span>
            文章评论
          </a>
        
      </div>
    </footer>
  </div>
  </div>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2021/02/13/SyntaxError-EOL-while-scanning-string-literal/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">下一篇</strong>
      <div class="article-nav-title">
        
          SyntaxError EOL while scanning string literal
        
      </div>
    </a>
  
  
    <a href="/2021/02/08/Linux%20%E4%BF%AE%E6%94%B9%E6%96%87%E4%BB%B6%E6%9D%83%E9%99%90/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">上一篇</strong>
      <div class="article-nav-title">Linux 修改文件权限</div>
    </a>
  
</nav>

  
</article>


  
    <section id="comments" class="vcomment">
  
    </section>
  
</section>
      
      <aside id="sidebar">
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">近期文章</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2022/04/10/Flask-SQLAlchemy%E6%B5%AE%E7%82%B9%E6%95%B0%E7%B1%BB%E5%9E%8BFloat%E4%B8%A2%E5%A4%B1%E7%B2%BE%E5%BA%A6%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95/">Flask SQLAlchemy 浮点数类型Float 丢失精度 解决方法</a>
          </li>
        
          <li>
            <a href="/2022/04/09/iphone%E8%BF%9B%E5%85%A5DFU%E6%A8%A1%E5%BC%8F%E6%96%B9%E6%B3%95/">iphone进入DFU模式方法</a>
          </li>
        
          <li>
            <a href="/2022/04/09/u%E7%9B%98%E5%90%AF%E5%8A%A8%E8%BF%9B%E5%85%A5PE%E7%B3%BB%E7%BB%9F%E5%BF%AB%E6%8D%B7%E9%94%AE/">U盘启动进入PE系统 快捷键</a>
          </li>
        
          <li>
            <a href="/2022/04/09/you-get%20%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B/">you-get 使用教程</a>
          </li>
        
          <li>
            <a href="/2022/04/09/youtube-dl%20%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B/">youtube-dl 使用教程</a>
          </li>
        
      </ul>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">标签</h3>
    <div class="widget">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/Chrome/" rel="tag">Chrome</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Docker/" rel="tag">Docker</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Flask/" rel="tag">Flask</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Github/" rel="tag">Github</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Hexo/" rel="tag">Hexo</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Linux/" rel="tag">Linux</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Markdown/" rel="tag">Markdown</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/MySQL/" rel="tag">MySQL</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Navicat/" rel="tag">Navicat</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/OS/" rel="tag">OS</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/PicGo/" rel="tag">PicGo</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Python/" rel="tag">Python</a><span class="tag-list-count">10</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/SQLite/" rel="tag">SQLite</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Selenium/" rel="tag">Selenium</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Software/" rel="tag">Software</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Typora/" rel="tag">Typora</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Ubuntu/" rel="tag">Ubuntu</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/iphone/" rel="tag">iphone</a><span class="tag-list-count">1</span></li></ul>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">归档</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2022/04/">四月 2022</a><span class="archive-list-count">11</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/03/">三月 2021</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/02/">二月 2021</a><span class="archive-list-count">16</span></li></ul>
    </div>
  </div>

  
</aside>
      
    </div>
    <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2022 HDUZN hduzn@vip.qq.com<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
      .
      Theme by <a href="https://github.com/sun11/hexo-theme-paperbox" target="_blank">Paperbox</a>
    </div>
  </div>
</footer>
  </div>
  <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">首页</a>
  
    <a href="/archives" class="mobile-nav-link">归档</a>
  
    <a href="/books" class="mobile-nav-link">推荐阅读</a>
  
  <a href="#search" class="mobile-nav-link st-search-show-outputs">搜索</a>
</nav>

  
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    menuSettings: {
      zoom: "None"
    },
    showMathMenu: false,
    jax: ["input/TeX","output/CommonHTML"],
    extensions: ["tex2jax.js"],
    TeX: {
      extensions: ["AMSmath.js","AMSsymbols.js"],
      equationNumbers: {
        autoNumber: "AMS"
      }
    },
  });
</script>

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/mathjax/2.6.1/MathJax.js"></script>



<!-- totop start -->
<div id="totop">
	<a title="返回顶部"></a>
</div>
<!-- totop end -->

<!-- swiftype search start -->

<!-- swiftype search end -->



<!-- valine start -->

    
<script src="https://cdn.jsdelivr.net/npm/valine@1.3.10/dist/Valine.min.js"></script>

  <script>
      var GUEST_INFO = ['nick','mail','link'];
      var guest_info = 'nick,mail,link'.split(',').filter(function(item){
          return GUEST_INFO.indexOf(item) > -1
      });
      var notify = 'false' == true;
      var verify = 'false' == true;
      new Valine({
          el: '.vcomment',
          notify: notify,
          verify: verify,
          appId: "UVs2AheLuqJbRc85LQv7vzMz-gzGzoHsz",
          appKey: "y98dsYB3ugs25U2vgNWTb3m7",
          placeholder: "请在此输入您的留言",
          pageSize:'10',
          avatar:'mm',
          lang:'zh-cn'
      });
  </script>
  

<!-- valine end -->

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<script src="//cdnjs.cloudflare.com/ajax/libs/lrsjng.jquery-qrcode/0.12.0/jquery.qrcode.min.js"></script>




<script src="/js/script.js"></script>


</div>
</body>
</html>
